package com.gaojice.server.http;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.URISyntaxException;

import javax.net.ServerSocketFactory;

import com.gaojice.server.http.service.RequestHandler;

public class HttpService extends Thread {
	private ServerSocket serverSocket;

	public void stopService() {
		if (serverSocket != null && !serverSocket.isClosed()) {
			try {
				serverSocket.close();
			} catch (IOException e) {
				e.printStackTrace();
			}

		}

	}

	public void run() {
		int port = 8888;
		try {
			serverSocket = ServerSocketFactory.getDefault().createServerSocket(
					port);
			System.out.println("Server started on port: " + port);
		} catch (IOException e) {
			e.printStackTrace();
		}
		while (true) {
			Socket socket = null;
			try {
				socket = serverSocket.accept();
				new RequestHandler().handRequest(socket);
			} catch (ArrayIndexOutOfBoundsException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} catch (URISyntaxException e) {
				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				if (socket != null && !socket.isClosed()) {
					try {
						socket.close();
					} catch (IOException e) {
						e.printStackTrace();
					}

				}

			}
		}

	}
}
